import * as echarts from 'echarts';
import { isNil } from "lodash-es";
import React from "react";
import { IProvinceGDP } from "../../core/interface";

export interface IProps {
    year: number;
    yearlyData: IProvinceGDP[];
}

/** 健康设施对比图 */
const HealthChart: React.FC<IProps> = (props) => {
    const { year, yearlyData } = props;
    const containerRef = React.useRef<HTMLDivElement>(null);
    const chartRef = React.useRef<echarts.ECharts>(null);

    const renderChart = () => {
        if (isNil(containerRef.current)) return;
        const { width, height } = containerRef.current.getBoundingClientRect();
        const chartWidth = width;
        const chartHeight = height;
        const option = {
            title: {
                text: `${year}年各省份健康设施对比`
            },
            xAxis: {
                type: 'category',
                data: yearlyData.map(item => item.province),
                axisTick: {
                    alignWithLabel: true
                },
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    data: yearlyData.map(item => item.healthInstitutions ?? 0),
                    type: 'bar',
                    name: '健康设施',
                }
            ],
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
        };
        if (chartRef.current) {
            // update
            chartRef.current.setOption(option);
        } else {
            const chart = echarts.init(containerRef.current, undefined, {
                height: chartHeight,
                width: chartWidth,
            });

            chart.setOption(option);
            chartRef.current = chart;
        }
    };

    React.useEffect(() => {
        renderChart();
    }, [yearlyData]);

    return (
        <div className="bar-chart-for-health-contaienr" ref={containerRef} style={{
            width: '50%',
            height: '100%',
            display: 'inline-block',
            verticalAlign: 'top',
        }}>

        </div>
    );
};

export default HealthChart;